<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="本文将重点分析Dubbo的两个重要特性：泛化调用与泛化实现。 1、泛化引用：  通常是服务调用方没有引入API包，也就不包含接口中的实体类，故服务调用方只能提供Map形式的数据，由服务提供者根据Map转化成对应的实体。 2、泛化实现  泛化实现，是指服务提供者未引入API包，也就不包含接口用于传输数据的实体类，故客户端发起调用前，需要将mode转化为Map。 从上面分析，其实所谓的泛化本质上就是">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Dubbo 泛化调用与泛化实现原理">
<meta property="og:url" content="https://www.codingw.net/posts/5f7d793b.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="本文将重点分析Dubbo的两个重要特性：泛化调用与泛化实现。 1、泛化引用：  通常是服务调用方没有引入API包，也就不包含接口中的实体类，故服务调用方只能提供Map形式的数据，由服务提供者根据Map转化成对应的实体。 2、泛化实现  泛化实现，是指服务提供者未引入API包，也就不包含接口用于传输数据的实体类，故客户端发起调用前，需要将mode转化为Map。 从上面分析，其实所谓的泛化本质上就是">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdn.net/20181005211034328?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20181005211118267?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="article:published_time" content="2020-12-01T11:30:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:09:00.430Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdn.net/20181005211034328?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/5f7d793b.html"/>





  <title>源码分析Dubbo 泛化调用与泛化实现原理 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/5f7d793b.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Dubbo 泛化调用与泛化实现原理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-12-01T19:30:01+08:00">
                2020-12-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dubbo/" itemprop="url" rel="index">
                    <span itemprop="name">dubbo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/5f7d793b.html" class="leancloud_visitors" data-flag-title="源码分析Dubbo 泛化调用与泛化实现原理">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><ul>
<li>本文将重点分析Dubbo的两个重要特性：泛化调用与泛化实现。<br> 1、泛化引用：<br> <img src="https://img-blog.csdn.net/20181005211034328?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="在这里插入图片描述"><br> 通常是服务调用方没有引入API包，也就不包含接口中的实体类，故服务调用方只能提供Map形式的数据，由服务提供者根据Map转化成对应的实体。<br> 2、泛化实现<br> <img src="https://img-blog.csdn.net/20181005211118267?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="在这里插入图片描述"><br> 泛化实现，是指服务提供者未引入API包，也就不包含接口用于传输数据的实体类，故客户端发起调用前，需要将mode转化为Map。<br> 从上面分析，其实所谓的泛化本质上就是Map与Bean的转换。</li>
</ul>
<span id="more"></span>

<h2 id="3、源码分析客户端用于泛化调用的过滤器GenericImplFilter"><a href="#3、源码分析客户端用于泛化调用的过滤器GenericImplFilter" class="headerlink" title="3、源码分析客户端用于泛化调用的过滤器GenericImplFilter"></a>3、源码分析客户端用于泛化调用的过滤器GenericImplFilter</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br></pre></td><td class="code"><pre><span class="line">public Result invoke(Invoker&lt;?&gt; invoker, Invocation invocation) throws RpcException &#123;</span><br><span class="line">        String generic &#x3D; invoker.getUrl().getParameter(Constants.GENERIC_KEY);</span><br><span class="line">        if (ProtocolUtils.isGeneric(generic)                                                                                  &#x2F;&#x2F; @1</span><br><span class="line">                &amp;&amp; !Constants.$INVOKE.equals(invocation.getMethodName())</span><br><span class="line">                &amp;&amp; invocation instanceof RpcInvocation) &#123;</span><br><span class="line">            RpcInvocation invocation2 &#x3D; (RpcInvocation) invocation;</span><br><span class="line">            String methodName &#x3D; invocation2.getMethodName();</span><br><span class="line">            Class&lt;?&gt;[] parameterTypes &#x3D; invocation2.getParameterTypes();</span><br><span class="line">            Object[] arguments &#x3D; invocation2.getArguments();</span><br><span class="line"></span><br><span class="line">            String[] types &#x3D; new String[parameterTypes.length];</span><br><span class="line">            for (int i &#x3D; 0; i &lt; parameterTypes.length; i++) &#123;</span><br><span class="line">                types[i] &#x3D; ReflectUtils.getName(parameterTypes[i]);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            Object[] args;</span><br><span class="line">            if (ProtocolUtils.isBeanGenericSerialization(generic)) &#123;</span><br><span class="line">                args &#x3D; new Object[arguments.length];</span><br><span class="line">                for (int i &#x3D; 0; i &lt; arguments.length; i++) &#123;</span><br><span class="line">                    args[i] &#x3D; JavaBeanSerializeUtil.serialize(arguments[i], JavaBeanAccessor.METHOD);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                args &#x3D; PojoUtils.generalize(arguments);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            invocation2.setMethodName(Constants.$INVOKE);</span><br><span class="line">            invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES);</span><br><span class="line">            invocation2.setArguments(new Object[]&#123;methodName, types, args&#125;);</span><br><span class="line">            Result result &#x3D; invoker.invoke(invocation2);</span><br><span class="line"></span><br><span class="line">            if (!result.hasException()) &#123;</span><br><span class="line">                Object value &#x3D; result.getValue();</span><br><span class="line">                try &#123;</span><br><span class="line">                    Method method &#x3D; invoker.getInterface().getMethod(methodName, parameterTypes);</span><br><span class="line">                    if (ProtocolUtils.isBeanGenericSerialization(generic)) &#123;</span><br><span class="line">                        if (value &#x3D;&#x3D; null) &#123;</span><br><span class="line">                            return new RpcResult(value);</span><br><span class="line">                        &#125; else if (value instanceof JavaBeanDescriptor) &#123;</span><br><span class="line">                            return new RpcResult(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) value));</span><br><span class="line">                        &#125; else &#123;</span><br><span class="line">                            throw new RpcException(</span><br><span class="line">                                    &quot;The type of result value is &quot; +</span><br><span class="line">                                            value.getClass().getName() +</span><br><span class="line">                                            &quot; other than &quot; +</span><br><span class="line">                                            JavaBeanDescriptor.class.getName() +</span><br><span class="line">                                            &quot;, and the result is &quot; +</span><br><span class="line">                                            value);</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125; else &#123;</span><br><span class="line">                        return new RpcResult(PojoUtils.realize(value, method.getReturnType(), method.getGenericReturnType()));</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; catch (NoSuchMethodException e) &#123;</span><br><span class="line">                    throw new RpcException(e.getMessage(), e);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; else if (result.getException() instanceof GenericException) &#123;</span><br><span class="line">                GenericException exception &#x3D; (GenericException) result.getException();</span><br><span class="line">                try &#123;</span><br><span class="line">                    String className &#x3D; exception.getExceptionClass();</span><br><span class="line">                    Class&lt;?&gt; clazz &#x3D; ReflectUtils.forName(className);</span><br><span class="line">                    Throwable targetException &#x3D; null;</span><br><span class="line">                    Throwable lastException &#x3D; null;</span><br><span class="line">                    try &#123;</span><br><span class="line">                        targetException &#x3D; (Throwable) clazz.newInstance();</span><br><span class="line">                    &#125; catch (Throwable e) &#123;</span><br><span class="line">                        lastException &#x3D; e;</span><br><span class="line">                        for (Constructor&lt;?&gt; constructor : clazz.getConstructors()) &#123;</span><br><span class="line">                            try &#123;</span><br><span class="line">                                targetException &#x3D; (Throwable) constructor.newInstance(new Object[constructor.getParameterTypes().length]);</span><br><span class="line">                                break;</span><br><span class="line">                            &#125; catch (Throwable e1) &#123;</span><br><span class="line">                                lastException &#x3D; e1;</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                    if (targetException !&#x3D; null) &#123;</span><br><span class="line">                        try &#123;</span><br><span class="line">                            Field field &#x3D; Throwable.class.getDeclaredField(&quot;detailMessage&quot;);</span><br><span class="line">                            if (!field.isAccessible()) &#123;</span><br><span class="line">                                field.setAccessible(true);</span><br><span class="line">                            &#125;</span><br><span class="line">                            field.set(targetException, exception.getExceptionMessage());</span><br><span class="line">                        &#125; catch (Throwable e) &#123;</span><br><span class="line">                            logger.warn(e.getMessage(), e);</span><br><span class="line">                        &#125;</span><br><span class="line">                        result &#x3D; new RpcResult(targetException);</span><br><span class="line">                    &#125; else if (lastException !&#x3D; null) &#123;</span><br><span class="line">                        throw lastException;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; catch (Throwable e) &#123;</span><br><span class="line">                    throw new RpcException(&quot;Can not deserialize exception &quot; + exception.getExceptionClass() + &quot;, message: &quot; + exception.getExceptionMessage(), e);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            return result;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        if (invocation.getMethodName().equals(Constants.$INVOKE)                             &#x2F;&#x2F; @2</span><br><span class="line">                &amp;&amp; invocation.getArguments() !&#x3D; null</span><br><span class="line">                &amp;&amp; invocation.getArguments().length &#x3D;&#x3D; 3</span><br><span class="line">                &amp;&amp; ProtocolUtils.isGeneric(generic)) &#123;</span><br><span class="line"></span><br><span class="line">            Object[] args &#x3D; (Object[]) invocation.getArguments()[2];</span><br><span class="line">            if (ProtocolUtils.isJavaGenericSerialization(generic)) &#123;</span><br><span class="line"></span><br><span class="line">                for (Object arg : args) &#123;</span><br><span class="line">                    if (!(byte[].class &#x3D;&#x3D; arg.getClass())) &#123;</span><br><span class="line">                        error(byte[].class.getName(), arg.getClass().getName());</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; else if (ProtocolUtils.isBeanGenericSerialization(generic)) &#123;</span><br><span class="line">                for (Object arg : args) &#123;</span><br><span class="line">                    if (!(arg instanceof JavaBeanDescriptor)) &#123;</span><br><span class="line">                        error(JavaBeanDescriptor.class.getName(), arg.getClass().getName());</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            ((RpcInvocation) invocation).setAttachment(</span><br><span class="line">                    Constants.GENERIC_KEY, invoker.getUrl().getParameter(Constants.GENERIC_KEY));</span><br><span class="line">        &#125;</span><br><span class="line">        return invoker.invoke(invocation);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：该分支是泛化实现，如果是泛化实现，则根据generic的值进行序列化，然后调用$invoke方法，因为服务端实现为泛化实现，所有的服务提供者实现GenericeServer#$invoker方法，其实现方式就是将Bean转换成Map。这些细节将在服务端GenericFilter序列中详细讲解。</p>
<p>代码@2：泛化引用，调用方是直接通过GenericService#$invoke方法进行调用，以此来区分是泛化调用还是泛化引用，那不经要问，为什么invoker.getUrl().getParameter(Constants.GENERIC_KEY)中获取的generic参数到底是&lt; dubbo:service/&gt;中配置的还是&lt; dubbo:reference/&gt;中配置的呢？其实不难理解：</p>
<ol>
<li>dubbo:servcie未配置而dubbo:reference配置了，则代表的是消费端的，必然是泛化引用。</li>
<li>dubbo:servcie配置而dubbo:reference未配置了，则代表的是服务端的，必然是泛化实现。</li>
<li>如果两者都配置了，generic以消费端为主。消费端参数与服务端参数的合并在服务发现时，注册中心首先会将服务提供者的URL通知消费端，然后消费端会使用当前的配置与服务提供者URL中的配置进行合并，如遇到相同参数，则消费端覆盖服务端。</li>
</ol>
<blockquote>
<p>注：这里我就不深入去探讨其实现细节，因为这部分在下文源码分析GenericFilter时会详细介绍Map与Bean转换的细节，包含是否序列化，之所以这里没有细说，主要是因为我先看的是GenericFilter。</p>
</blockquote>
<h2 id="4、源码分析泛化引用-GenericFilter（服务提供者）"><a href="#4、源码分析泛化引用-GenericFilter（服务提供者）" class="headerlink" title="4、源码分析泛化引用 GenericFilter（服务提供者）"></a>4、源码分析泛化引用 GenericFilter（服务提供者）</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br></pre></td><td class="code"><pre><span class="line">@Activate(group &#x3D; Constants.PROVIDER, order &#x3D; -20000)</span><br><span class="line">public class GenericFilter implements Filter &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public Result invoke(Invoker&lt;?&gt; invoker, Invocation inv) throws RpcException &#123;</span><br><span class="line">        if (inv.getMethodName().equals(Constants.$INVOKE)</span><br><span class="line">                &amp;&amp; inv.getArguments() !&#x3D; null</span><br><span class="line">                &amp;&amp; inv.getArguments().length &#x3D;&#x3D; 3</span><br><span class="line">                &amp;&amp; !ProtocolUtils.isGeneric(invoker.getUrl().getParameter(Constants.GENERIC_KEY))) &#123;       &#x2F;&#x2F; @1</span><br><span class="line">            String name &#x3D; ((String) inv.getArguments()[0]).trim();</span><br><span class="line">            String[] types &#x3D; (String[]) inv.getArguments()[1];</span><br><span class="line">            Object[] args &#x3D; (Object[]) inv.getArguments()[2];</span><br><span class="line">            try &#123;</span><br><span class="line">                Method method &#x3D; ReflectUtils.findMethodByMethodSignature(invoker.getInterface(), name, types);             &#x2F;&#x2F; @2</span><br><span class="line">                Class&lt;?&gt;[] params &#x3D; method.getParameterTypes();</span><br><span class="line">                if (args &#x3D;&#x3D; null) &#123;</span><br><span class="line">                    args &#x3D; new Object[params.length];</span><br><span class="line">                &#125;</span><br><span class="line">                String generic &#x3D; inv.getAttachment(Constants.GENERIC_KEY);</span><br><span class="line">                if (StringUtils.isEmpty(generic)</span><br><span class="line">                        || ProtocolUtils.isDefaultGenericSerialization(generic)) &#123;                                                             &#x2F;&#x2F; @3</span><br><span class="line">                    args &#x3D; PojoUtils.realize(args, params, method.getGenericParameterTypes());</span><br><span class="line">                &#125; else if (ProtocolUtils.isJavaGenericSerialization(generic)) &#123;                                                             &#x2F;&#x2F; @4</span><br><span class="line">                    for (int i &#x3D; 0; i &lt; args.length; i++) &#123;</span><br><span class="line">                        if (byte[].class &#x3D;&#x3D; args[i].getClass()) &#123;</span><br><span class="line">                            try &#123;</span><br><span class="line">                                UnsafeByteArrayInputStream is &#x3D; new UnsafeByteArrayInputStream((byte[]) args[i]);</span><br><span class="line">                                args[i] &#x3D; ExtensionLoader.getExtensionLoader(Serialization.class)</span><br><span class="line">                                        .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)</span><br><span class="line">                                        .deserialize(null, is).readObject();</span><br><span class="line">                            &#125; catch (Exception e) &#123;</span><br><span class="line">                                throw new RpcException(&quot;Deserialize argument [&quot; + (i + 1) + &quot;] failed.&quot;, e);</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125; else &#123;</span><br><span class="line">                            throw new RpcException(</span><br><span class="line">                                    &quot;Generic serialization [&quot; +</span><br><span class="line">                                            Constants.GENERIC_SERIALIZATION_NATIVE_JAVA +</span><br><span class="line">                                            &quot;] only support message type &quot; +</span><br><span class="line">                                            byte[].class +</span><br><span class="line">                                            &quot; and your message type is &quot; +</span><br><span class="line">                                            args[i].getClass());</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; else if (ProtocolUtils.isBeanGenericSerialization(generic)) &#123;                                                 &#x2F;&#x2F; @5</span><br><span class="line">                    for (int i &#x3D; 0; i &lt; args.length; i++) &#123;</span><br><span class="line">                        if (args[i] instanceof JavaBeanDescriptor) &#123;</span><br><span class="line">                            args[i] &#x3D; JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) args[i]);</span><br><span class="line">                        &#125; else &#123;</span><br><span class="line">                            throw new RpcException(</span><br><span class="line">                                    &quot;Generic serialization [&quot; +</span><br><span class="line">                                            Constants.GENERIC_SERIALIZATION_BEAN +</span><br><span class="line">                                            &quot;] only support message type &quot; +</span><br><span class="line">                                            JavaBeanDescriptor.class.getName() +</span><br><span class="line">                                            &quot; and your message type is &quot; +</span><br><span class="line">                                            args[i].getClass().getName());</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                Result result &#x3D; invoker.invoke(new RpcInvocation(method, args, inv.getAttachments()));    &#x2F;&#x2F; @6</span><br><span class="line">                if (result.hasException()</span><br><span class="line">                        &amp;&amp; !(result.getException() instanceof GenericException)) &#123;</span><br><span class="line">                    return new RpcResult(new GenericException(result.getException()));</span><br><span class="line">                &#125;</span><br><span class="line">                if (ProtocolUtils.isJavaGenericSerialization(generic)) &#123;                                                        &#x2F;&#x2F; @7</span><br><span class="line">                    try &#123;</span><br><span class="line">                        UnsafeByteArrayOutputStream os &#x3D; new UnsafeByteArrayOutputStream(512);</span><br><span class="line">                        ExtensionLoader.getExtensionLoader(Serialization.class)</span><br><span class="line">                                .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)</span><br><span class="line">                                .serialize(null, os).writeObject(result.getValue());</span><br><span class="line">                        return new RpcResult(os.toByteArray());</span><br><span class="line">                    &#125; catch (IOException e) &#123;</span><br><span class="line">                        throw new RpcException(&quot;Serialize result failed.&quot;, e);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; else if (ProtocolUtils.isBeanGenericSerialization(generic)) &#123;</span><br><span class="line">                    return new RpcResult(JavaBeanSerializeUtil.serialize(result.getValue(), JavaBeanAccessor.METHOD));</span><br><span class="line">                &#125; else &#123;</span><br><span class="line">                    return new RpcResult(PojoUtils.generalize(result.getValue()));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; catch (NoSuchMethodException e) &#123;</span><br><span class="line">                throw new RpcException(e.getMessage(), e);</span><br><span class="line">            &#125; catch (ClassNotFoundException e) &#123;</span><br><span class="line">                throw new RpcException(e.getMessage(), e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        return invoker.invoke(inv);  </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：如果方法名为$invoker，并且只有3个参数，并且服务端实现为非返回实现，则认为本次服务调用时客户端泛化引用服务端，客户端的泛化调用，需要将请求参数反序列化为该接口真实的pojo对象。<br>代码@2：根据接口名（API类）、方法名、方法参数类型列表，根据反射机制获取对应的方法。<br>代码@3：处理普通的泛化引用调用，即处理&lt;dubbo:referecnce generic=”true”  …/&gt;,只需要将参数列表Object[]反序列化为pojo即可，具体的反序列化为PojoUtils#realize,其实现原理如下：<br>在JAVA的世界中，pojo通常用map来表示，也就是一个Map可以用来表示一个对象的值，那从一个Map如果序列化一个对象呢？其关键的要素是要在Map中保留该对象的类路径名。例如现在有这样一个对象：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public class Student &#123;</span><br><span class="line">	private int id;</span><br><span class="line">	private String name;</span><br><span class="line">	private Team team;</span><br><span class="line">	&#x2F;&#x2F;省略get set方法</span><br><span class="line">&#125;</span><br><span class="line">public class Team &#123;</span><br><span class="line">	private int id;</span><br><span class="line">	private String name;</span><br><span class="line">	&#x2F;&#x2F; 省略其他属性与set get方法</span><br><span class="line">&#125;</span><br><span class="line">用Map表示Student为：</span><br><span class="line">&#123;</span><br><span class="line">	“class”:&quot;somepackeage.Student&quot;,</span><br><span class="line">	&quot;id&quot;:1,</span><br><span class="line">	&quot;name&quot;:&quot;dingw&quot;,</span><br><span class="line">	&quot;team&quot;:</span><br><span class="line">	&#123;</span><br><span class="line">		&quot;class&quot; : &quot;somepackage.Team&quot;,</span><br><span class="line">		&quot;id&quot;:2,</span><br><span class="line">		&quot;name&quot;:&quot;t&quot;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>也就是通过class来标识该Map需要反序列化的pojo类型。<br>代码@4：处理&lt; dubbo:reference generic=”nativejava” /&gt; 启用泛化引用，并使用nativejava序列化参数，在服务端这边通过nativejava反序列化参数成pojo对象。<br>代码@5：处理&lt; dubbo:reference generic=”bean” /&gt; 启用泛化引用，并使用javabean序列化参数，在服务端这边通过javabean反序列化参数成pojo对象。<br>代码@6：序列化API方法中声明的类型，构建new RpcInvocation(method, args, inv.getAttachments())调用环境，继续调用后续过滤器。<br>代码@7：处理执行结果，如果是nativejava或bean，则需要对返回结果序列化，如果是generic=true，则使用PojoUtils.generalize序列化，也即将pojo序列化为Map。<br>泛化调用与泛化引用，就介绍到这里了。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/70022ae6.html" rel="next" title="源码分析Dubbo异步调用与事件回调机制">
                <i class="fa fa-chevron-left"></i> 源码分析Dubbo异步调用与事件回调机制
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/b3d9d24a.html" rel="prev" title="源码分析Dubbo tps过滤器器实现原理">
                源码分析Dubbo tps过滤器器实现原理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%E5%AE%A2%E6%88%B7%E7%AB%AF%E7%94%A8%E4%BA%8E%E6%B3%9B%E5%8C%96%E8%B0%83%E7%94%A8%E7%9A%84%E8%BF%87%E6%BB%A4%E5%99%A8GenericImplFilter"><span class="nav-number">1.</span> <span class="nav-text">3、源码分析客户端用于泛化调用的过滤器GenericImplFilter</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%E6%B3%9B%E5%8C%96%E5%BC%95%E7%94%A8-GenericFilter%EF%BC%88%E6%9C%8D%E5%8A%A1%E6%8F%90%E4%BE%9B%E8%80%85%EF%BC%89"><span class="nav-number">2.</span> <span class="nav-text">4、源码分析泛化引用 GenericFilter（服务提供者）</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
